package com.auxgroup.smarthome.business.service;

import com.auxgroup.bridge.app.inner.vo.DeviceInfoNewVo;
import com.auxgroup.bridge.business.inner.vo.DeviceExportDataVo;
import com.auxgroup.bridge.business.inner.vo.DeviceListVo;
import com.auxgroup.bridge.business.inner.vo.UserDeviceListVo;
import com.auxgroup.smarthome.business.service.inner.AppUserDBInnerService;
import com.auxgroup.smarthome.business.service.inner.DeviceInnerService;
import com.auxgroup.smarthome.business.service.inner.FeignAppFilterFaultService;
import com.auxgroup.smarthome.business.vo.AppFilterFaultVo;
import com.auxgroup.smarthome.business.vo.DeviceDetailVo;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.enterprise.service.DeviceManageService;
import com.auxgroup.smarthome.enterpriseapi.requestbody.SearchDeviceWiFiBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.WIFIDeviceList;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.syscode.BusinessCode;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.utils.PageContent;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/8/16 17:34.
 */
@Service
public class DeviceService {
    @Autowired
    private DeviceInnerService deviceInnerService;
    @Autowired
    private AppUserDBInnerService appUserDBInnerService;
    @Autowired
    private DeviceManageService deviceManageService;
    @Autowired
    private ObjectRedis objectRedis;
    @Autowired
    private FeignAppFilterFaultService feignAppFilterFaultService;

    public ApiResponse<Page<DeviceListVo>> getDeviceList(String modelId, String keywords, String deviceStatus, Integer page, Integer size) {
        ApiResponse<PageContent<DeviceListVo>> apiResponse = deviceInnerService.getDeviceList(modelId, keywords, deviceStatus, page, size);
        Page<DeviceListVo> pageContent = apiResponse.getData().convertPage();
        return new ApiResponse(apiResponse.getCode(), apiResponse.getMessage(), pageContent);
    }

    /**
     * 获取设备列表不分页-导出数据
     * @param modelId
     * @param keywords
     * @param deviceStatus
     * @return
     */
    public ApiResponse<List<DeviceListVo>> getDeviceListByNotPage(String modelId, String keywords, String deviceStatus) {
        return deviceInnerService.getDeviceListByNoPage(modelId, keywords, deviceStatus);
    }

    /**
     * 导出设备数据
     * @param modelId
     * @param keywords
     * @param deviceStatus
     * @return
     */
    public ApiResponse<List<DeviceExportDataVo>> getDeviceExportData(String modelId, String deviceStatus, String keywords) {
        return deviceInnerService.getDeviceExportData(modelId, keywords, deviceStatus);
    }

    /**
     * 从Pass拉取设备详情信息
     * @param productKey
     * @param did
     * @return
     */
    public ApiResponse<DeviceDetailVo> getDeviceDetail(String productKey, String did) {
        SearchDeviceWiFiBody body = new SearchDeviceWiFiBody();
        body.setType("did");
        body.setVal(did);
        ApiResponse<WIFIDeviceList> apiResponse = deviceManageService.searchWiFiDevice(productKey, body);
        if(apiResponse.getCode() != 200) {
            return (ApiResponse)apiResponse;
        }
        List<WIFIDeviceList.WIFIDeviceInfo> wifiDeviceInfos = apiResponse.getData().getObjects();
        if(wifiDeviceInfos.size() <=  0) {
            return ApiResponse.prompt(BusinessCode.DEVICE_NOT_FOUND);

        }
        WIFIDeviceList.WIFIDeviceInfo wifiDeviceInfo = wifiDeviceInfos.get(0);
        DeviceDetailVo deviceDetailVo = new DeviceDetailVo(wifiDeviceInfo);
        ApiResponse<DeviceInfoNewVo> deviceInfoNewVoApi = deviceInnerService.getDeviceInfoNewVoByMac(wifiDeviceInfo.getMac());
        if (deviceInfoNewVoApi.isNotErrorCode()) {
            DeviceInfoNewVo deviceInfoNewVo = deviceInfoNewVoApi.getData();
            if (StringUtils.isNotEmpty(deviceInfoNewVo.getLongitude()) && StringUtils.isNotEmpty(deviceInfoNewVo.getLatitude())) {
                deviceDetailVo.setLongitude(deviceInfoNewVo.getLongitude());
                deviceDetailVo.setLatitude(deviceInfoNewVo.getLatitude());
            }
        }
        return ApiResponse.ok(deviceDetailVo);
    }

    /**
     * 获取滤网寿命
     * @param mac
     * @return
     */
    public ApiResponse getMeshLife(String mac) {
        String redisKey = CachedConsant.DEVICE_FILTER_FAULT_PREFIX+mac;
        ApiResponse<AppFilterFaultVo> apiResponse = feignAppFilterFaultService.getFilterFault(mac);
        AppFilterFaultVo appFilterFaultVo = apiResponse.getData();
        // 滤网寿命, 默认未使用
        int meshLife;
        int bootTime = 0;
        if(null != appFilterFaultVo) {
            bootTime = appFilterFaultVo.getBootTime();
        }
        Long bootTimeRedis = objectRedis.get(redisKey, Long.class);

        if(bootTimeRedis != null) {
            Instant instant = Instant.ofEpochMilli(bootTimeRedis);
            Duration duration = Duration.between(LocalDateTime.ofInstant(instant, NewDateUtils.getBeijingZoneId()), LocalDateTime.now(NewDateUtils.getBeijingZoneId()));
            bootTime += duration.toMinutes();
        }

        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        // 滤网寿命阈值
        float meshLifeThresholdValue = 500*60f;
        int result = Float.valueOf(numberFormat.format(bootTime / meshLifeThresholdValue*100)).intValue();
        if(result > 100) {
            meshLife = 0;
        } else {
            meshLife = 100 - result;
        }
        return ApiResponse.ok(meshLife);
    }

    /**
     * 获取用户设备列表
     * @param uid
     * @param page
     * @param size
     * @return
     */
    public ApiResponse<Page<UserDeviceListVo>> getUserDeviceList(String uid, Integer page, Integer size) {
        ApiResponse<PageContent<UserDeviceListVo>> apiResponse = appUserDBInnerService.getUserDeviceList(uid, page, size);
        Page<UserDeviceListVo> pageContent = apiResponse.getData().convertPage();
        return new ApiResponse(apiResponse.getCode(), apiResponse.getMessage(), pageContent);
    }

}
